package com.zhangln.mountbuzhou.config;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.zhangln.mountbuzhou.dto.SnowIdDto;
import com.zhangln.mountbuzhou.common.SnowIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;


/**
 * @author sherry
 * @description
 * @date Create in 2019/12/6
 * @modified By:
 */
@EnableTransactionManagement
@Configuration
@MapperScan(basePackages = {"com.zhangln.mountbuzhou.mapper"})
@Slf4j
public class MyBatisPlusConfig {

    @Value("${spring.application.name}")
    private String appName;
    private final RedisTemplate redisTemplate;

    public MyBatisPlusConfig(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 乐观锁
     *
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

    @Bean
    public IdentifierGenerator idGenerator() {
        SnowIdDto snowIdDto = SnowIdUtil.calculateDataIdAndWorkId2(redisTemplate, appName);
        log.info("初始化id生成器:dataCenterId:{},workerId:{}", snowIdDto.getDataCenterId(), snowIdDto.getWorkerId());
        return new DefaultIdentifierGenerator(snowIdDto.getWorkerId(), snowIdDto.getDataCenterId());
    }

}